//
//  YSFeedbackCtrl.m
//  Yueshi
//
//  Created by Northwan on 15/8/7.
//  Copyright (c) 2015年 悦食中国. All rights reserved.
//  意见反馈

#import "YSFeedbackCtrl.h"
#import "YSComtBottomView.h"
#import "YSFeedbackCell.h"
#import "YSMineDataTool.h"

@interface YSFeedbackCtrl ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate,YSComtBottomViewDelegate>
@property (strong, nonatomic) YSComtBottomView *bottomView;
@property (strong, nonatomic)  UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *itemArray;

@end

@implementation YSFeedbackCtrl

-(NSMutableArray *)itemArray{
    if(!_itemArray){
        _itemArray = [NSMutableArray array];
    }
    return _itemArray;
}

-(BOOL)shouldLogin{
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.fd_interactivePopDisabled = YES;
    [self.navigationItem setTitle: @"意见反馈"];
    [self registNortif];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH-NavWithStatusBarH-self.bottomView.height)];
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tableView setBackgroundColor:PUBLIC_BG];
    [self.view addSubview:self.tableView];
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestData)];
    [self.tableView.header beginRefreshing];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (!self.bottomView) {
        YSComtBottomView *view = [YSComtBottomView bottomView];
        [view setDelegate:self];
        view.width = SCREENW;
        view.height = 50;
        view.y = SCREENH - view.height - NavWithStatusBarH;
        [self.view addSubview:view];
        self.bottomView = view;
        
        //如果有未发布的内容则从缓存中取出&显示
        NSString *tempString = [DefaultsHelper stringForKey:kCacheFeedBackString];
        if(!ISBLANK(tempString)){
            view.commentTextView.text = tempString;
            view.publishBtn.enabled = YES;
        }
    }
    
    [self.bottomView.commentTextView resignFirstResponder];
}

-(void)keyboardWillChangeFrame:(NSNotification *)notif{
        // 1.获取键盘的Y值
        NSDictionary *dict  = notif.userInfo;
        CGRect keyboardFrame = [dict[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        CGFloat keyboardY = keyboardFrame.origin.y;
        // 获取动画执行时间
        CGFloat duration = [dict[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        // 2.计算需要移动的距离
        CGFloat translationY = keyboardY - self.view.frame.size.height-NavWithStatusBarH;
        [UIView animateWithDuration:duration delay:0.0 options:7 << 16 animations:^{
            // 需要执行动画的代码
            self.view.transform = CGAffineTransformMakeTranslation(0, translationY);
            CGFloat y = keyboardY - self.bottomView.height - NavWithStatusBarH;
            
            y = y > self.view.height - self.bottomView.height
                  ? self.view.height - self.bottomView.height
                  :y-translationY;
            
            self.bottomView.y = y;
        } completion:^(BOOL finished) {
            // 动画执行完毕执行的代码
        }];
}

- (IBAction)tapAction:(id)sender {
    [self.bottomView.commentTextView resignFirstResponder];
}

-(void)registNortif{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateNewMeesage:) name:kNewChatMessageContentNortif object:nil];
}

-(void)updateNewMeesage:(NSNotification *)nortif{
    NSString *string = [nortif object];
    YSFeedbackItem *message  = [YSFeedbackItem objectWithKeyValues:string];
    YSFeedbackItemFrame *frame = [[YSFeedbackItemFrame alloc] init];
    frame.msg = message;
    [self.itemArray addObject:frame];
    [self.tableView reloadData];
     [self scrollToBottom];
}

-(void)publish:(NSString *)text{
    [YSMineDataTool sendMessage:text messageType:0 success:^(YSSendMessageRes *result) {
        if (result.isSucc){
            YSFeedbackItem *message = [YSFeedbackItem new];
            message.content = text;
            message.messageId = result.messageId;
            message.fromType = FeedbackMsgFromSendType;
            YSFeedbackItemFrame *frame = [[YSFeedbackItemFrame alloc] init];
            frame.msg = message;
            [self.itemArray addObject:frame];
            [self.tableView reloadData];
            [self scrollToBottom];
            // 清空缓存内容,清空输入框
            [DefaultsHelper setObject:@"" forKey:kCacheFeedBackString];
            self.bottomView.commentTextView.text = nil;
            [self.bottomView.commentTextView resignFirstResponder];
            self.bottomView.height = 50;
            self.bottomView.y = SCREENH - self.bottomView.height - NavWithStatusBarH;
        }else{
            ShowEnterTips(result.data);
        }
    } failure:^(NSError *error) {
           ShowTips(kRequestFailure);
    }];
    //清空输入框
    self.bottomView.commentTextView.text = nil;
    [self.bottomView.commentTextView resignFirstResponder];
}

- (void)textViewTextDidChange:(CGFloat)offset{
    if (offset > 0){
        self.bottomView.y -= offset;
    }else{
        self.bottomView.y += fabs(offset);
    }
    self.tableView.height = SCREENH-NavWithStatusBarH-self.bottomView.height;
}

-(void)requestData{
    if(ISLOGIN){
        NSInteger firstId = 0;
        if (_itemArray.count){
           firstId = ((YSFeedbackItemFrame *)_itemArray.firstObject).msg.messageId;
        }
        [YSMineDataTool getMessageList:firstId messageType:0 success:^(YSFeedbackRes *result) {
            [UIUtil refreshComplete:self.tableView];
            if(result.isSucc){
                NSMutableArray *oldArray =  [NSMutableArray arrayWithArray:self.itemArray];
                [self.itemArray removeAllObjects];
                [self.itemArray addObjectsFromArray:[self itemArrayWithFrames:result.list]];
                [self.itemArray addObjectsFromArray:oldArray];
                [self.tableView reloadData];
                if(firstId == 0){
                    [self scrollToBottom];
                }else{//滚动到新消息的最后一条位置
                    NSIndexPath *path = [NSIndexPath indexPathForRow:result.list.count inSection:0];
                    [self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:NO];
                }

            }else{
                ShowEnterTips(result.data);
            }
        } failure:^(NSError *error) {
            ShowEnterTips(kRequestFailure);
            [UIUtil refreshComplete:self.tableView];
        }];
   }
}

-(void)scrollToBottom{
    if(self.itemArray.count){
        NSIndexPath *path = [NSIndexPath indexPathForRow:self.itemArray.count -1 inSection:0];
        [self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}

/**
 *  根据模型数组 转成 frame模型数据
 *
 */
- (NSArray *)itemArrayWithFrames:(NSArray *)list
{
    NSMutableArray *frames = [NSMutableArray array];
    for(YSFeedbackItem *msg in list) {
            YSFeedbackItemFrame *frame = [[YSFeedbackItemFrame alloc] init];
            frame.msg = msg;
            [frames addObject:frame];
     }
    return frames;
}

#pragma - mark UITableViewDataSource,UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.itemArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YSFeedbackCell *cell =  [YSFeedbackCell cellWithTableView:tableView];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setItemFrame:self.itemArray[indexPath.row]];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self.itemArray[indexPath.row] cellHeight];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.bottomView.commentTextView resignFirstResponder];
}

- (void)dealloc{
    if ([self.bottomView.commentTextView hasText]) {
        [DefaultsHelper setObject:self.bottomView.commentTextView.text forKey:kCacheFeedBackString];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
